#!/bin/bash

# return value using function output
function dbl() {
    read -p "Enter a value: " value
    echo $[ $value * 2 ]
}

result=`dbl`
echo "The new value is $result"

function mul() {
    echo $[ $1 * $2 ]
}

if [ $# -eq 2 ]; then
    value=`mul $1 $2`
    echo "The result is $value"
else
    echo "Usage: ./function.sh a b"
fi

# pass array
function testit() {
    local newarray
    newarray=(`echo "$@"`)
    echo "The new array value is: ${newarray[*]}"
}
myarray=(1 2 3 4 5)
echo "The original array is ${myarray[*]}"
testit ${myarray[*]}

# return array
function arraydblr() {
    local origarray
    local newarray
    local elements
    local i
    origarray=(`echo "$@"`)
    newarray=(`echo "$@"`)
    elements=$[ $# - 1 ]
    for (( i = 0; i <= $elements; i++ )) {
        newarray[$i]=$[ ${origarray[$i]} * 2 ]
    }
    echo ${newarray[*]}
}
myarray=(1 2 3 4 5)
echo "The original array is: ${myarray[*]}"
arg1=`echo ${myarray[*]}`
result=(`arraydblr $arg1`)
echo "The new array is: ${result[*]}"

# recursive
function factorial() {
    if [ $1 -eq 1 ]; then
        echo 1
    else
        local temp=$[ $1 - 1 ]
        local result=`factorial $temp`
        echo $[ $result * $1 ]
    fi
}
read -p "Enter value: " value
result=`factorial $value`
echo "The factorial of $value is: $result"


